package com.jianganming.nio.chat;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class ChatClient {
    private SocketChannel socketChannel;
    private Selector selector;
    private String userName;

    public ChatClient(){
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));
            socketChannel.configureBlocking(false);
            selector = Selector.open();
            socketChannel.register(selector,SelectionKey.OP_READ);
            userName = socketChannel.getLocalAddress().toString();
        }catch (Exception e){

        }
    }

    public void sendInfo(String msg){
        String info = userName+" 说:"+msg;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (Exception e){
            System.out.println("发送失败");
        }
    }

    public void readInfo(){
        try {
            int readChannels = selector.select();
            if(readChannels>0){
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    if(key.isReadable()){
                        readData(key);
                    }
                }
                iterator.remove();
            }
        }catch (Exception e){
            System.out.println("读取失败");
        }

    }

    private void readData(SelectionKey key)throws Exception {
        SocketChannel channel = (SocketChannel) key.channel();

        channel.configureBlocking(false);

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        int read = channel.read(byteBuffer);

        System.out.println(new String(byteBuffer.array(),0,read));
    }

    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        new Thread(()->{
            while (true){
                chatClient.readInfo();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();

        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNext()){
            String msg = scanner.next();
            chatClient.sendInfo(msg);
        }

    }
}
